package com.atguigu.study.safe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class NotSafeDemo {
    //一个线程start()两次 不合法的线程状态异常
    //Java.util.ConcurrentModificationException 并发修改异常
    public static void main(String[] args) {
//        Map<String, String> map = new ConcurrentHashMap();//Collections.synchronizedMap(new HashMap<>());//new HashSet<>();
// Node<K,V> 数组 加链表 加红黑树
        Map<String, String> map = new ConcurrentHashMap<>();//Collections.synchronizedMap(new HashMap<>());//new HashMap<>();
        //并发安全的HashMap,底层采用数组 链表 红黑树 内部大量采用CAS操作. 并发控制使用synchronized和CAS来操作实现的
        //分段锁 只锁一个房间 其他房间不锁
        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
               map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,6));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }
    public static void setNotSafe() {
//        Set<String> set =new CopyOnWriteArraySet<>(); //Collections.synchronizedSet(new HashSet<>());//new HashSet<>();
        Set<String> set = new CopyOnWriteArraySet<>();//Collections.synchronizedSet(new HashSet<>());//new HashSet<>();
        //Collections.synchronizedSet(new HashSet<>());是在add方法里面加锁  读多写少
        //CopyOnWriteArrayList<>() 读写分离,写时复制(写时复制出来一份,写加锁,查看不加锁,本体给他人查看,复制体继续写,完事后用复制体覆盖本体)
        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }
    public static void listNotSafe() {
//        List<String> list = new CopyOnWriteArrayList<>(); //Collections.synchronizedList(new ArrayList<>());//new Vector<>();//new ArrayList<>();
        List<String> list = new CopyOnWriteArrayList<>();//Collections.synchronizedList(new ArrayList<>());//new Vector<>();//new ArrayList<>();
        //Collections.synchronizedList(new ArrayList<>());是在add方法里面加锁
        //CopyOnWriteArrayList<>() 读写分离,写时复制(写时复制出来一份,写加锁,查看不加锁,本体给他人查看,复制体继续写,完事后用复制体覆盖本体)
        for (int i = 1; i <= 100; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }


    }
}
